<?php
declare (strict_types = 1);

namespace app\user\controller;

use app\common\lib\email\Email;
use app\common\lib\message\Message;
use think\Exception;

class Login extends Ucenter
{
    public function register(){
        if($this->request->isPost()){
            $data = $this->request->post();

            if(!isset($data['password'])){
                throw new Exception('请输入密码');
            }

            (new \app\user\model\User())->register($data);
        }

		return $this->fetch();
    }

    public function login(){
        if($this->request->isPost()){
			try{

				$result = (new \app\user\model\User())->login(
					$this->request->post('username/s',''),
					$this->request->post('password/s',''),
					$this->request->post('remeberme/b',false)
				);
				return $this->response->success($result);
			}catch (\Exception $exception){
				return $this->response->error($exception->getMessage());
			}
        }
	    return $this->fetch();
    }

	public function mobile(){
		return $this->response->error('功能正在开发');
	}

	public function email(){
		if($this->request->isPost()){
			$email = $this->request->post('email/s','');
			$code = $this->request->post('code/s','');
			if(!(new Email())->verify((int)$code,$email,'login')){
				return $this->response->error('邮箱验证码错误');
			}
			try{

				return $this->response->success((new \app\user\model\User())->email($email),'登录成功');
			}catch (\Exception $exception){
				return $this->response->error($exception->getMessage());
			}
		}
		return $this->fetch();
	}

	public function sendVerify(string $type = 'email'){
		try{
			$message = (new Message($type))->send(
				$this->request->get('target/s',''),
				$this->request->get('scene/s','')
			);
			return $this->response->success();
		}catch (\Exception $exception){
			return $this->response->error($exception->getMessage());
		}

	}
}
